﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Referee
{
    public static partial class contest
    {
        public static bool updataRanklist(Sql.ContestStatus sts, string connstr)
        {
            var sql = new Sql.DatabaseDataContext(connstr);
            if (DateTime.Now > sql.Contest.Where(row => row.cid == sts.cid).FirstOrDefault().overTime
            || DateTime.Now < sql.Contest.Where(row => row.cid == sts.cid).FirstOrDefault().startTime)
                return false;
            var ts = sql.ContestStatus.Where(row => (sts.username == row.username && row.ps == sts.ps && row.cid == sts.cid && row.status > 3));
            var fs = sql.ContestStatus.Where(row => (sts.username == row.username && row.ps == sts.ps && row.cid == sts.cid && row.status == 3 && row.rid != sts.rid));

            if (sql.ContestStatus.Where(row => row.username == sts.username) == null)
            {
                return false;
            }
            var con = sql.Contest.FirstOrDefault(row => row.cid == sts.cid);
            if (con == null) return false;
            if (fs.Count() > 1) return true;
            var rlp = sql.Ranklist.FirstOrDefault(row => row.username == sts.username && row.cid == sts.cid);
            if (rlp == null)
            {
                rlp = new Sql.Ranklist
                {
                    cid = sts.cid,
                    username = sts.username,
                    usetime = 0,
                    submit = 0,
                    ac = 0
                };
                sql.Ranklist.InsertOnSubmit(rlp);
            }
            bool pass = sql.ContestSolve.Where(row => row.cid == sts.cid && row.username == sts.username && row.ps == sts.ps && row.ac > 1).Any();
            if (sts.status == 3 && !pass)
            {
                int notpass = sql.ContestSolve.FirstOrDefault(row => row.cid == sts.cid && row.username == sts.username && row.ps == sts.ps).submit - 1;
                rlp.usetime += (int)(DateTime.Now - con.startTime).TotalMinutes + notpass * 20;
                rlp.ac++;
                rlp.submit++;
            }
            sql.SubmitChanges();
            return true;
        }
    }
}
